<template>
  <el-Dialog :title="formData.id?'编辑房产':'添加房产'" :visible="isShowDialog" @close="btnCancel">
    <el-form ref="addProperty" :model="formData" :rules="rules" label-width="80px">

      <el-form-item label="经纪">
        <el-select v-model="formData.agent" placeholder="请选择">
          <el-option
            v-for="item in agents"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="分类">
        <el-select v-model="formData.category" placeholder="请选择">
          <el-option
            v-for="item in category"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item prop="title" label="标题">
        <el-input v-model="formData.title" />
      </el-form-item>

      <el-form-item label="标签">
        <el-tag
          v-for="tag in formData.tags"
          :key="tag"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-if="inputVisible"
          ref="saveTagInput"
          v-model="inputValue"
          class="input-new-tag"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        />
        <el-button v-else class="button-new-tag" size="small" @click="showInput">添加标签</el-button>
      </el-form-item>

      <el-form-item label="地址">
        <el-row type="flex">
          <el-cascader v-model="cityValue" :options="address" :props="{label:'name',value:'name'}" @change="cityChange" />
          <el-input v-model="formData.address" />
        </el-row>
      </el-form-item>

      <el-form-item label="价格">
        <el-input v-model="formData.price" />
      </el-form-item>

      <el-form-item prop="desc" label="描述">
        <el-input v-model="formData.desc" type="textarea" />
      </el-form-item>

      <el-form-item label="内容">
        <vue-editor v-model="formData.content" />
      </el-form-item>

      <el-form-item label="介绍图片">
        <ImageUpload ref="introducePic" :num="4" />
      </el-form-item>

      <el-form-item label="封面">
        <ImageUpload ref="coverPic" />
      </el-form-item>

    </el-form>
    <template #footer>
      <el-button type="primary" size="small" @click="btnOk">确定</el-button>
      <el-button size="small" @click="btnCancel">取消</el-button>
    </template>
  </el-Dialog>
</template>

<script>
import mapData from '../mapData/data.json'
import { VueEditor } from 'vue2-editor'
import 'quill/dist/quill.snow.css'
import { getAgentList } from '@/api/agent'
import { getCategoryList } from '@/api/category'
import { getPropertyDetail, editProperty, addProperty } from '@/api/property'
export default {
  components: {
    VueEditor
  },
  props: {
    isShowDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {

      // 富文本
      config: {},
      // 标签类
      inputVisible: false,
      inputValue: '',

      // 下拉选项类
      // 经纪人
      agents: [],

      // 分类
      category: [],
      // 地址
      address: mapData.data,
      cityValue: '',

      // 表单数据
      formData: {
        title: '',
        desc: '',
        image: '',
        agent: '',
        conent: '',
        address: '',
        price: '',
        photos: [],
        tags: ['近地铁', '舒适'],
        category: ''
      },

      // 校验规则
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '请添加描述', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 获取经纪
    this.getAgentList()
    // 获取分类
    this.getCategoryList()
  },

  methods: {
    // 获取所有经纪
    async getAgentList() {
      const { data } = await getAgentList()
      // console.log(136, data)
      this.agents = data
      this.$emit('sendAgents', this.agents)
    },
    // 获取所有分类
    async getCategoryList() {
      const { data } = await getCategoryList()
      console.log(141, data)
      this.category = data
      this.$emit('sendCategory', this.category)
    },
    // 删除标签
    handleClose(tag) {
      this.formData.tags.splice(this.formData.tags.indexOf(tag), 1)
    },
    // 显示输入框
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 输入框确认
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.formData.tags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 选择城市
    cityChange(city) {
      this.formData.address = city.join('/')
    },

    // 确认按钮
    async btnOk() {
      try {
        // 校验表单
        console.log(200, this.$refs.addProperty)
        await this.$refs.addProperty.validate()
        const fileList1 = this.$refs.introducePic.fileList
        const fileList2 = this.$refs.coverPic.fileList
        const arr1 = fileList1.map(item => item.url)
        const arr2 = fileList1.map(item => item.status)
        // console.log(arr2)
        if (fileList1.length === 0 || fileList2.length === 0) {
          this.$message.warning('请添加图片')
          return
        }

        if (arr2.some(item => item !== 'success')) {
          this.$message.error('请等待图片上传完毕')
          return
        }
        if (fileList2[0] && fileList2[0].status !== 'success') {
          this.$message.error('请等待图片上传完毕')
          return
        }
        // 发请求
        if (this.formData.id) {
        // 编辑
          await editProperty({ ...this.formData, image: fileList2[0] ? fileList2[0].url : '', photos: arr1 })
        } else {
        // 新增
          await addProperty({ ...this.formData, image: fileList2[0] ? fileList2[0].url : '', photos: arr1 })
        }

        console.log(186, this.formData)
        // 提示用户
        this.$message.success('操作成功')
        // 关闭弹窗
        this.$emit('update:isShowDialog', false)
        // 刷新页面
        this.$emit('reloadPage')
        this.cityValue = ''
      } catch (error) {
        console.log(error)
      }
    },
    btnCancel() {
      // 清空数据
      this.formData = {
        title: '',
        desc: '',
        image: '',
        agent: '',
        conent: '',
        address: '',
        price: '',
        photos: [],
        tags: [],
        category: ''
      }
      this.cityValue = ''
      this.$refs.introducePic.fileList = []
      this.$refs.coverPic.fileList = []
      // 清理校验结果
      this.$refs.addProperty.resetFields()
      // 关闭弹窗
      this.$emit('update:isShowDialog', false)
    },
    // 获取房产详情
    async getPropertyDetail(id) {
      const { data } = await getPropertyDetail(id)
      // console.log(123)
      // console.log(205, data)
      this.formData = data

      const newArr = []

      this.formData.photos.map(item => {
        newArr.push({ url: item })
      })

      this.$refs.introducePic.fileList = newArr
      // console.log(224, newArr)

      if (this.formData.image) {
        this.$nextTick(() => {
          // console.log(209, this.$refs.coverPic.fileList)
          this.$refs.coverPic.fileList = [
            { url: this.formData.image }
          ]
        })
      }
      // this.$refs.introducePic.fileList = this.formData.photos
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
